import type { Directive } from 'vue'
// Intersection API
const ob = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const animation = map.get(entry.target)
      animation && animation.play()
      ob.unobserve(entry.target)
    }
  })
  // console.log(entries)
})
const map = new WeakMap()

const isBelowViewport = (el: HTMLElement) => {
  const bounding = el.getBoundingClientRect()
  return bounding.top >= window.innerHeight || bounding.bottom <= 0
}

const fadeIn: Directive = {
  mounted(el: HTMLElement) {
    if (!isBelowViewport(el)) return
    // web Animation API
    const animation = el.animate(
      [
        {
          transform: 'translateY(100px)',
          opacity: 0.5
        },
        {
          transform: 'translateY(0)',
          opacity: 1
        }
      ],
      {
        duration: 500,
        easing: 'ease-out',
        fill: 'forwards'
      }
    )
    animation.pause()
    map.set(el, animation)
    ob.observe(el)
  },
  unmounted: (el) => {
    ob.unobserve(el)
  }
}

export default fadeIn
